package org.goldfish.message_board01.dao;

import org.goldfish.message_board01.entity.User;
import org.goldfish.message_board01.util.DatabaseConnectionManager;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDAO extends AbstractDAO{
    public UserDAO() {
        this.dbManager = new DatabaseConnectionManager();
    }

    /**
     * Retrieves a User by their name.
     *
     * @param name The username.
     * @return The User object if found, null otherwise.
     */
    public User getUserByName(String name) {
        String sql = "SELECT name, password FROM user WHERE name = ?";
        Connection connection;
        User user = null;
        try {
            connection = dbManager.getConnection();
            try (
                    PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
                preparedStatement.setString(1, name);
                try (ResultSet resultSet = preparedStatement.executeQuery()) {
                    if (resultSet.next()) {
                        user = new User(
                                resultSet.getString("name"),
                                resultSet.getString("password")
                        );
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace(System.err);
        }
        return user;
    }

    /**
     * Inserts a new User into the database.
     *
     * @param user The User to insert.
     * @return true if insertion is successful, false otherwise.
     */
    public boolean insertUser(User user) {
        String sql = "INSERT INTO user (name, password) VALUES (?, ?)";
        Connection connection = null;
        try {
             connection = dbManager.getConnection();
            try (
                    PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
                preparedStatement.setString(1, user.getName());
                preparedStatement.setString(2, user.getPassword());
                return preparedStatement.executeUpdate() > 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            dbManager.releaseConnection(connection);
        }
        return false;
    }
}
